using System;
using System.Collections.Generic;
using System.Data;

using System.Linq;
using LuaInterface;

namespace RwotaStatistic.LuaToMssql
{
	public static class LuaTableConvert
	{
		public static DataTable ToDataTable(LuaTable luaTable, int factsLevel)
		{
			var dt = new DataTable();
			var list = GetColumns(luaTable, factsLevel, 0, null);
			foreach (var strings in list)
			{
				for (int i = 0; i < strings.GetLength(0); i++)
				{
					var name = strings[i, 0];
					if (!dt.Columns.Contains(name))
					{
						dt.Columns.Add(name, typeof(string));
					}
				}
			}

			foreach (var strings in list)
			{
				var row = dt.NewRow();
				for (int i = 0; i < strings.GetLength(0); i++)
				{
					var name = strings[i, 0];
					row[name] = strings[i, 1];
				}
				dt.Rows.Add(row);
			}

			return dt;
		}

		private static List<string[,]> GetColumns(LuaTable root, int factsLevel, int currentLevel, object key)
		{
			var res = new List<string[,]>();
			var keys = root.Keys.Cast<object>()
						.ToArray();

			if (factsLevel == currentLevel)
			{
				var vals = new string[keys.Length + 1, 2];
				vals[0, 0] = "Id";
				vals[0, 1] = key.ToString();
				for (int i = 0; i < keys.Length; i++)
				{
					var cKey = keys[i];
					var val = root[cKey];
					var j = i + 1;
					vals[j, 0] = cKey.ToString();
					if (val is LuaTable)
					{
						var sRes = ((LuaTable)val).Values
							.Cast<object>()
							.Select(s => s.ToString())
							.Aggregate((a, item) => string.Format("{{\"{0}\", \"{1}\"}}", a, item));
						vals[j, 1] = sRes;
					}
					else
					{
						vals[j, 1] = val == null ? null : val.ToString();
					}
				}
				res.Add(vals);
			}
			else
			{
				for (int i = 0; i < keys.Length; i++)
				{
					var cKey = keys[i];
					var val = root[cKey];
					if (!(val is LuaTable))
					{
						continue;
					}
					res.AddRange(GetColumns((LuaTable)val, factsLevel, currentLevel + 1, cKey));
				}

			}
			return res;
		}
	}
}